<template>
  <!-- 常见问题 -->
  <div class="quota-container">
    <div class="filter-container">
      <k-button class="top-btn" value="新增" @click.native="addItemDialog" />
      <k-button class="top-btn" value="删除" @click.native="delItemData" />
    </div>
    <!--表格相关 -->
    <el-table
      ref="dragTable"
      :data="listData"
      fit
      border
      row-key="id"
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column min-width="60px" type="selection" align="center" fixed="left" />
      <el-table-column prop="title" min-width="150px" label="周期" align="center" show-overflow-tooltip fixed="left" />
      <el-table-column prop="wanPrice" min-width="150px" label="额度" align="center" show-overflow-tooltip />
      <el-table-column prop="prompt" min-width="150px" label="超额提示" align="center" show-overflow-tooltip />
      <el-table-column prop="friendPrompt" min-width="150px" label="友情提示文案" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.friendPrompt }}
        </template>
      </el-table-column>
      <el-table-column min-width="100px" label="友情提示" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.friendStatus"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="开"
            inactive-text="关"
            :active-value="1"
            :inactive-value="2"
            @change="itemOnlineState(scope.row)"
          />
          <!-- @change="itemOnlineState($event,scope)" -->
        </template>
      </el-table-column>
      <el-table-column prop="friendPrice" min-width="150px" label="触发金额" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.friendPrice }}
        </template>
      </el-table-column>
      <el-table-column min-width="200px" label="配置时间" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column min-width="200px" label="额度限制总开关" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-text="开"
            inactive-text="关"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            :active-value="1"
            :inactive-value="2"
            @change="handelUpdate(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createByname" min-width="100px" label="配置人" align="center" show-overflow-tooltip />
      <el-table-column min-width="150px" label="操作" align="center" fixed="right">
        <template slot-scope="scope">
          <k-button class="table-btn" value="修改/查看" @click.native="itemUpdateDialog(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <!-- <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="getList"
    /> -->

    <!-- 添加 弹窗 -->
    <k-dialog
      :show-hide.sync="addBox.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      :title="textMap[dialogStatus]"
      class="addBox-dialog"
      :show-foot="false"
      :two-btn="true"
      @click="saveItemDataClick"
    >
      <el-form :model="addItemInfo" label-width="auto" class="form-modify">
        <el-form-item label="范围设置：" :required="true">
          <el-select v-model="addItemInfo.limitDay" placeholder="请选择范围">
            <el-option label="每日" :value="1" />
            <el-option label="每周" :value="2" />
            <el-option label="每月" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="额度：" :required="true">
          <el-input v-model="addItemInfo.wanPrice" onkeyup="value=value.replace(/[^0-9]/g,'')" show-word-limit placeholder="请输入额度">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="智能提示：">
          <div>
            <div> {{ tipsValue }}</div>
            <div><k-button value="使用此提示" @click.native="addItemInfo.prompt = tipsValue" /></div>
          </div>
        </el-form-item>
        <el-form-item label="提示文案：" :required="true">
          <el-input v-model="addItemInfo.prompt" :rows="5" show-word-limit type="textarea" />
        </el-form-item>
        <el-form-item label="友情提醒：">
          <el-switch
            v-model="addItemInfo.friendStatus"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="开"
            inactive-text="关"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
        <el-form-item label="提示方式：">
          <!-- <el-input v-model="addItemInfo.friendType" show-word-limit placeholder="请选择范围" /> -->
          {{ textFiltration(addItemInfo.friendType || 1) }}
        </el-form-item>
        <el-form-item label="触发：" :required="addItemInfo.friendStatus==1">
          消费金额到达
          <el-input v-model="addItemInfo.friendPrice" onkeyup="value=value.replace(/[^0-9]/g,'')" style="width:200px" show-word-limit placeholder="金额">
            <template slot="append">元</template>
          </el-input>
          时
        </el-form-item>
        <el-form-item v-if="friendPromptsValue" label="智能提示：">
          <div>
            <div> {{ friendPromptsValue }}</div>
            <div><k-button value="使用此提示" @click.native="addItemInfo.friendPrompt = friendPromptsValue" /></div>
          </div>
        </el-form-item>
        <el-form-item label="文案：" :required="addItemInfo.friendStatus==1">
          <el-input v-model="addItemInfo.friendPrompt" :rows="5" show-word-limit type="textarea" />
        </el-form-item>
      </el-form>
    </k-dialog>

  </div>
</template>

<script>
import Sortable from 'sortablejs'

import {
  sort
} from '@/api/settings/settings.js'
import { userqutasttingSelectUserQuotaSettingList, userqutasttingInsertUserQuotaSetting, userqutasttingDeleteUserQuotaSettingById, userqutasttingUpdateUserQuotaSetting } from '@/api/hq/index.js'
export default {
  data() {
    return {
      dialogStatus: 'create',
      textMap: {
        update: '修改',
        create: '创建'
      },

      timeValue: '',
      timeCotinue: '',

      addItemInfo: {
        id: '',
        limitDay: undefined, // 1日 2星期 3月  范围设置
        wanPrice: undefined, // 额度
        prompt: undefined, // 提示文案
        friendStatus: 2, // 是否开启友情提醒  1开|2关
        friendType: 1, // 提醒方式  默认 1 文案提醒
        friendPrice: undefined, // 触发
        friendPrompt: undefined // 编辑文案
      },
      addBox: {
        showHide: false
      },

      listData: [],
      sortable: null,

      itemIds: []
    }
  },
  computed: {
    tipsValue() {
      return `亲爱的9宝，您本日消费数已达当日最高额度，今日将不能继续消费。非常感谢您的陪伴和大力支持，同时也请您请理性消费！`
    },
    friendPromptsValue() {
      if (!this.addItemInfo.friendPrice || this.addItemInfo.friendStatus !== 1) return
      return `亲爱的9宝，您本日消费数已超${this.addItemInfo.friendPrice}个95币，非常感谢您的陪伴和大力支持，同时也请您理性消费！`
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 等级箱子列表页加载数据
    getList() {
      userqutasttingSelectUserQuotaSettingList({}).then(res => {
        this.listData = res.data.data
      })
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.listData.splice(evt.oldIndex, 1)[0]
          this.listData.splice(evt.newIndex, 0, targetRow)
          const ids = this.listData.map(item => item.id)
          sort({
            ids: ids
          }).then(res => {
            this.getList()
          })
        }
      })
    },
    addItemDialog() {
      this.addBox.showHide = true
      this.dialogStatus = 'create'
      this.$resetForm(this.addItemInfo)
    },
    itemUpdateDialog(row) {
      this.dialogStatus = 'update'
      this.addBox.showHide = true
      this.addItemInfo = { ...row }
    },

    // 添加|修改
    saveItemDataClick() {
      if (!this.addItemInfo.limitDay) return this.$message.error('范围设置不能为空')
      if (!this.addItemInfo.wanPrice) return this.$message.error('额度不能为空')
      if (!this.addItemInfo.prompt) return this.$message.error('提示文案不能为空')
      if (this.addItemInfo.friendStatus == 1) {
        if (!this.addItemInfo.friendPrice) return this.$message.error('触发金额不能为空')
        if (!this.addItemInfo.friendPrompt) return this.$message.error('友情提示提示文案不能为空')
      }
      if (this.dialogStatus == 'create') {
        userqutasttingInsertUserQuotaSetting(this.addItemInfo).then(res => {
          if (!res.data.success) return this.$message.error(res.data.msg)
          this.$message.success('操作成功')
          this.addBox.showHide = false
          this.getList()
          this.$resetForm(this.addItemInfo)
        })
      } else {
        userqutasttingUpdateUserQuotaSetting(this.addItemInfo).then(res => {
          if (!res.data.success) return this.$message.error(res.data.msg)
          this.$message.success('操作成功')
          this.addBox.showHide = false
          this.getList()
          this.$resetForm(this.addItemInfo)
        })
      }
    },

    // 开关
    itemOnlineState(row) {
      const flag = row.friendStatus // 保存点击之后v-modeld的值(true，false)
      row.friendStatus = row.friendStatus == 1 ? 2 : 1 // 保持switch点击前的状态
      this.$confirm(`是否 ${flag == 1 ? '开启' : '关闭'}${row.title} 的友情提示?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const parameter = {
          id: row.id, 	// 保存点击之后v-model的值(id)或传递给页面的
          limitDay: row.limitDay,
          wanPrice: row.wanPrice,
          prompt: row.prompt,
          friendStatus: row.friendStatus == 1 ? 2 : 1,
          friendPrice: row.friendPrice,
          friendPrompt: row.friendPrompt
        }
        if (flag == 1) {
          userqutasttingUpdateUserQuotaSetting(parameter).then(res => {
            if (!res.data.success) return this.$message.error(res.data.msg)
            this.getList()
            this.$resetForm(this.addItemInfo)
            this.$message.success(res.data.msg)
          })
        } else {
          userqutasttingUpdateUserQuotaSetting(parameter).then(res => {
            if (!res.data.success) return this.$message.error(res.data.msg)
            this.getList()
            this.$resetForm(this.addItemInfo)
            this.$message.success(res.data.msg)
          })
        }
      }).catch(() => {
        this.$message.info('取消操作！')
      })
    },

    handelUpdate(row) {
      const flag = row.status // 保存点击之后v-modeld的值(true，false)
      console.log('flag: ', flag)
      row.status = row.status == 1 ? 2 : 1 // 保持switch点击前的状态
      this.$confirm(`是否 ${flag == 1 ? '开启' : '关闭'}${row.title} 的额度限制?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const { id } = row
        const statushq = row.status == 1 ? 2 : 1
        console.log('statushq: ', statushq)

        if (flag == 1) {
          userqutasttingUpdateUserQuotaSetting({ id, status: statushq }).then(res => {
            if (!res.data.success) return this.$message.error(res.data.msg)
            this.getList()
            this.$resetForm(this.addItemInfo)
            this.$message.success(res.data.msg)
          })
        } else {
          userqutasttingUpdateUserQuotaSetting({ id, status: statushq }).then(res => {
            if (!res.data.success) return this.$message.error(res.data.msg)
            this.getList()
            this.$resetForm(this.addItemInfo)
            this.$message.success(res.data.msg)
          })
        }
      }).catch(() => {
        this.$message.info('取消操作！')
      })
    },
    delItemData() {
      if (this.itemIds.length == 0) {
        this.$message.error('最少选择一项')
        return
      }
      this.$confirm('确定删除选中项么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userqutasttingDeleteUserQuotaSettingById({
          ids: this.itemIds
        }).then(res => {
          if (res.data.success) {
            this.$message.success('操作成功')
            this.getList()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    textFiltration(type) {
      const textMap = {
        1: '友情提示'
      }
      return textMap[type]
    },
    // 选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      const ids = val.map(item => item.id)
      this.itemIds = ids
    }
  }
}
</script>
<style>
	.sortable-ghost {
		opacity: .8;
		color: #fff !important;
		background: #3b425d !important;
	}
</style>
<style lang="scss" scoped>
	$mainColor:#3b425d; // 主色调
	$disabledColor: #909399; //禁用色
	$hoverColor:#1D143C; // 鼠标停留主色调浅色

	::v-deep .el-select .el-input.is-focus .el-input__inner {
		border-color: $mainColor;
	}

	::v-deep .el-input__inner:focus {
		border-color: $mainColor;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.price-input {
		width: 70px;
	}

	.addBox-dialog {
		::v-deep .el-dialog__body {
			padding: 10px 80px;
		}

		::v-deep .image-slot {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 100%;
			background: #f5f7fa;
			color: #909399;
			font-size: 40px;
		}

		::v-deep .el-textarea__inner:focus {
			outline: 0;
			border-color: $mainColor;
		}
	}

	.upload-btn {
		font-size: 14px;
		color: #ffffff;
	}

	.dialog-warningSetting {
		::v-deep.el-input {
			width: 110px;
		}

		.price-input {
			width: 100px;
		}

		.el-icon {

			&-circle-plus,
			&-remove {
				font-size: 22px;
				color: #3b425d;
				margin-left: 10px;

			}
		}

		ul {
			list-style-type: none;
			margin-top: 20px;
			padding: 0;

			li {
				margin: 0 0 30px 0px;
				display: flex;
				flex-direction: row;
				align-items: center;

				i {
					color: #D1D5DD;
				}
			}
		}

		.warning-title {
			font-size: 16px;
			color: #14162E;

			&-right {
				font-size: 16px;
				color: #14162E;
				margin-left: 80px;
			}

			&-right2 {
				font-size: 16px;
				color: #14162E;
				margin-left: 20px;
			}
		}
	}

	.table-btn {
		width: 90px;
		height: 35px;
		line-height: 35px;
		padding: 0;
		background: #e7ecf8;
		border: 1px solid $mainColor;
		border-radius: 8px;
		font-size: 14px;
		color: $mainColor;

		&:hover {
			background: $mainColor;
			color: #fff;
		}

		&:focus {
			background-color: #e7ecf8;
		}
	}

	.filter-container {
		width: 100%;
		height: 48px;
		line-height: 48px;
		margin-bottom: 30px;

		.filter-item {
			display: inline-block;
			vertical-align: middle;
			margin-bottom: 10px;
		}

		.top-btn {
			font-size: 14px;
			color: #ffffff;
		}

		.kInput {
			position: absolute;
			right: 20px;
		}
	}

	.chargeform {
		display: flex;
		flex-direction: row;
	}
</style>
